﻿using Common.Library;
using Common.Model;
using Container.Library;
using Dapper.Library;
using Mall.Model;
using Serialize.Library;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Mall.Logic
{
    /// <summary>
    /// 商品分类逻辑类
    /// </summary>
    public class GoodsCategoryServiceImpl : OperationLogicImpl, IGoodsCategoryService
    {
        #region 基础信息管理模块

        #region 信息查询

        /// <summary>
        /// 获取所有商品分类树状信息
        /// </summary>
        /// <returns></returns>
        public ResultJsonInfo<List<TreeInfo>> LoadAllTreeList() {

            var resultInfo = new ResultJsonInfo<List<TreeInfo>>();
            List<TreeInfo> listInfo = new List<TreeInfo>();

            using (var con = DataBase.GetConnection(DatabaseName.Sql_BUS_DB.ToString()))
            {
                var goodscategories = con.QuerySet<GoodsCategoriesEntity>()
                            .OrderBy(p => p.sort)
                            .ToList();
                if (goodscategories.Count > 0)
                {
                    TreeInfo categoriesInfo = new TreeInfo()
                    {
                        id = "",
                        title = "商品分类信息",
                        field = "商品分类信息",
                        spread = "true",
                        children = goodscategories.GetChildTreeInfo("")
                    };
                    listInfo.Add(categoriesInfo);
                    resultInfo.Code = ActionCodes.Success;
                    resultInfo.Data = listInfo;
                    resultInfo.Msg = "获取成功！";
                }
                else
                {
                    resultInfo.Msg = "获取所有商品分类树状信息失败！";
                }
            }
            return resultInfo;
        }

        /// <summary>
        /// 根据关键字获取所有的商品分类树状信息
        /// </summary>
        /// <param name="keyWords"></param>
        /// <returns></returns>
        public ResultJsonInfo<List<GoodsCategoryTreeInfo>> LoadTreeList(string keyWords)
        {
            var resultInfo = new ResultJsonInfo<List<GoodsCategoryTreeInfo>>();
            List<GoodsCategoryInfoResponse> listInfo = new List<GoodsCategoryInfoResponse>();

            using (var con = DataBase.GetConnection(DatabaseName.Sql_BUS_DB.ToString()))
            {
                var result = con.QuerySet<GoodsCategoriesEntity>();
                //所有商品分类
                var goodsCategoriesLists = new List<GoodsCategoriesEntity>();
                //这里获取所有，查询是否有兄弟节点
                var listInfoAll = result.OrderBy(p => p.sort).ToList();

                if (keyWords.IsNotNullOrEmpty())
                {
                    result.Where(p => p.name.Contains(keyWords));
                }
                //直接查询出的信息
                var queryInfo = result.OrderBy(p => p.sort).OrderBy(p => p.sort).ToList();

                var queryInfoRes = queryInfo.MapToList<GoodsCategoryInfoResponse>();
                foreach (var item in queryInfoRes)
                {
                    //NET算术运算溢出问题
                    item.have_elder = listInfoAll.Exists(p => p.sort < item.sort && p.id != item.id && p.parent_id == item.parent_id);
                    item.have_younger = listInfoAll.Exists(p => p.sort > item.sort && p.id != item.id && p.parent_id == item.parent_id);
                }
                //所有信息
                var listInfoAllRes = listInfoAll.MapToList<GoodsCategoryInfoResponse>();

                if (keyWords.IsNotNullOrEmpty())
                {
                    if (queryInfoRes.Count > 0)
                    {
                        for (int i = 0; i < queryInfoRes.Count; i++)
                        {
                            QueryParent(listInfoAllRes, queryInfoRes[i].id, ref listInfo);
                            QueryChildren(listInfoAllRes, queryInfoRes[0].id, ref listInfo);
                        }
                        queryInfoRes = listInfo;
                    }
                }

                if (queryInfoRes.Count > 0)
                {
                    resultInfo.Code = ActionCodes.Success;
                    resultInfo.Data = GetChildTreeInfo(queryInfoRes, "");
                    resultInfo.Msg = "获取成功！";
                }
                else
                {
                    resultInfo.Msg = "无对应值存在！";
                }
            }
            return resultInfo;
        }


        /// <summary>
        /// 指定ID ，向下查询商品分类所有的子节点------递归获取
        /// </summary>
        /// <param name="orgList"></param>
        /// <param name="parentId"></param>
        /// <returns></returns>
        private List<GoodsCategoryTreeInfo> GetChildTreeInfo(List<GoodsCategoryInfoResponse> orgList, string parentId)
        {
            List<GoodsCategoryTreeInfo> reultList = new List<GoodsCategoryTreeInfo>();
            //根据NodeID，获取当前子节点列表
            GoodsCategoryTreeInfo treeInfo = null;

            List<GoodsCategoryInfoResponse> chidList = orgList.FindAll(p => p.parent_id == parentId).ToList();

            if (chidList.Count > 0)
            {
                foreach (var item in chidList)
                {
                    treeInfo = new GoodsCategoryTreeInfo()
                    {
                        id = item.id,
                        parent_id = item.parent_id,
                        name = item.name,
                        sort = item.sort,
                        remarks = item.remarks,
                        have_elder = item.have_elder,
                        have_younger = item.have_younger,
                        children = new List<GoodsCategoryTreeInfo>()
                    };
                    //递归获取下一级
                    treeInfo.children = GetChildTreeInfo(orgList, item.id);
                    reultList.Add(treeInfo);
                }
            }
            return reultList;
        }


        /// <summary>
        /// 向上查询父级数据
        /// </summary>
        /// <param name="list">ALL</param>
        /// <param name="id"></param>
        /// <param name="resultList"></param>
        private void QueryParent(List<GoodsCategoryInfoResponse> list, string id, ref List<GoodsCategoryInfoResponse> resultList)
        {
            var info = list.Where(a => a.id == id).ToList();
            if (info.Count > 0)
            {
                resultList.Add(info[0]);
                if (info[0].parent_id != "" && info[0].parent_id != null)
                {
                    QueryParent(list, info[0].parent_id, ref resultList);
                }
            }
        }

        /// <summary>
        /// 向下查询子级数据
        /// </summary>
        /// <param name="list"></param>
        /// <param name="id"></param>
        /// <param name="resultList"></param>
        private void QueryChildren(List<GoodsCategoryInfoResponse> list, string id, ref List<GoodsCategoryInfoResponse> resultList)
        {

            var info = list.Where(a => a.id == id).ToList();
            if (info.Count > 0)
            {
                var xia = list.Where(a => a.parent_id == info[0].id).ToList();
                for (int i = 0; i < xia.Count; i++)
                {
                    resultList.Add(xia[i]);
                    QueryChildren(list, xia[i].id, ref resultList);
                }
            }
        }

        #endregion

        #region 更新操作

        /// <summary>
        /// 新增节点信息
        /// </summary>
        /// <param name="addInfo"></param>
        /// <returns></returns>
        public ResultJsonInfo<int> Addnode(GoodsCategoryAddRequest addInfo)
        {

            var resultInfo = new ResultJsonInfo<int>();
            using (var con = DataBase.GetConnection(DatabaseName.Sql_BUS_DB.ToString()))
            {
                if (addInfo.parent_id.IsNotNullOrEmpty())
                {
                    con.Transaction(tran =>
                    {
                        var result = 0;
                        var categoriesList = tran.QuerySet<GoodsCategoriesEntity>().ToList();

                        var categoriesInfo = categoriesList.Find(p => p.id == addInfo.parent_id);
                        if (categoriesInfo != null)
                        {
                            //查询出排序在该节点之后的所有节点
                            var sysDepartmentInfos = categoriesList.FindAll(p => p.sort > categoriesInfo.sort);
                            foreach (var item in sysDepartmentInfos)
                            {
                                item.sort = item.sort + 1;
                                tran.CommandSet<GoodsCategoriesEntity>().Update(item);
                            }

                            //插入数据
                            var infoEntity = addInfo.MapTo<GoodsCategoriesEntity>();
                            infoEntity.id = GuidHelper.GetGuid();
                            infoEntity.sort = categoriesInfo.sort + 1;
                            result = tran.CommandSet<GoodsCategoriesEntity>().Insert(infoEntity);

                            if (result > 0)
                            {
                                resultInfo.Code = ActionCodes.Success;
                                resultInfo.Data = result;
                                resultInfo.Msg = "新增子节点信息成功！";
                                AddOperationLog(OperationLogType.AddOperation, BusinessTitleType.GoodsCategoriesManage, $"新增子节点信息:{JsonHelper.ToJson(categoriesInfo)}");
                            }
                            else
                            {
                                resultInfo.Msg = "操作失败！";
                            }
                        }
                        else
                        {
                            resultInfo.Msg = "无对应父节点信息！";
                        }
                    });
                }
                else
                {
                    var result = 0;
                    var categoriesInfo = addInfo.MapTo<GoodsCategoriesEntity>();
                    //获取所有部门信息
                    var maxSort = con.QuerySet<GoodsCategoriesEntity>().Max(p => p.sort);
                    categoriesInfo.id = GuidHelper.GetGuid();
                    categoriesInfo.sort = maxSort + 1;

                    result = con.CommandSet<GoodsCategoriesEntity>().Insert(categoriesInfo);
                    if (result > 0)
                    {
                        resultInfo.Code = ActionCodes.Success;
                        resultInfo.Data = result;
                        resultInfo.Msg = "新增节点信息成功！";
                        AddOperationLog(OperationLogType.AddOperation, BusinessTitleType.GoodsCategoriesManage, $"新增节点信息:{JsonHelper.ToJson(categoriesInfo)}");
                    }
                    else
                    {
                        resultInfo.Msg = "操作失败！";
                    }
                }
            }
            return resultInfo;
        }

        /// <summary>
        /// 修改节点信息
        /// </summary>
        /// <param name="modifyInfo"></param>
        /// <returns></returns>
        public ResultJsonInfo<int> Modify(GoodsCategoryModifyRequest modifyInfo)
        {
            var resultInfo = new ResultJsonInfo<int>();
            using (var con = DataBase.GetConnection(DatabaseName.Sql_BUS_DB.ToString()))
            {
                var result = 0;

                var categoriesInfo = con.QuerySet<GoodsCategoriesEntity>().Where(p => p.id == modifyInfo.id).Get();

                if (categoriesInfo != null)
                {
                    categoriesInfo.name = modifyInfo.name;
                    categoriesInfo.img_url = modifyInfo.img_url;
                    categoriesInfo.remarks = modifyInfo.remarks;

                    result = con.CommandSet<GoodsCategoriesEntity>().Update(categoriesInfo);

                    if (result > 0)
                    {
                        resultInfo.Code = ActionCodes.Success;
                        resultInfo.Data = result;
                        resultInfo.Msg = "修改信息成功！";

                        AddOperationLog(OperationLogType.ModifyOperation, BusinessTitleType.GoodsCategoriesManage, $"新增根节点信息:{JsonHelper.ToJson(categoriesInfo)}");
                    }
                    else
                    {
                        resultInfo.Msg = "操作失败！";
                    }
                }
                else
                {
                    resultInfo.Msg = "无对应信息！";
                }
            }
            return resultInfo;
        }

        #endregion

        #region 移动顺序操作
        /// <summary>
        /// 移动顺序操作
        /// </summary>
        /// <param name="inputInfo"></param>
        /// <returns></returns>
        public ResultJsonInfo<int> Move(GoodsCategoryMoveRequest inputInfo)
        {
            var result = new ResultJsonInfo<int>();
            using (var con = DataBase.GetConnection(DatabaseName.Sql_BUS_DB.ToString()))
            {
                con.Transaction(tran =>
                {
                    //（1）所有
                    var allCategories = tran.QuerySet<GoodsCategoriesEntity>().OrderBy(p => p.sort).ToList();
                    //（2）当前
                    var currCategories = allCategories.Find(p => p.id == inputInfo.id);
                    //（3）当前功能兄弟节点
                    List<GoodsCategoriesEntity> brothersCategories = allCategories.FindAll(p => p.parent_id == currCategories.parent_id);

                    GoodsCategoriesEntity broCategories = null;
                    foreach (GoodsCategoriesEntity item in brothersCategories)
                    {
                        if (inputInfo.Flag == 1)//上移
                        {
                            if (item.sort < currCategories.sort){  broCategories = item; }
                            if (item.sort > currCategories.sort) {  break; } //找到上一个兄弟节点
                        }
                        else //下移
                        {
                            if (item.sort > currCategories.sort) { broCategories = item; break; } //找到下一个兄弟节点
                        }
                    }

                    List<GoodsCategoriesEntity> currCat = new List<GoodsCategoriesEntity>();
                    currCat.Add(currCategories);
                    GetMoveNode(allCategories, currCategories.id, currCat);

                    List<GoodsCategoriesEntity> moveFuns = new List<GoodsCategoriesEntity>();
                    moveFuns.Add(broCategories);
                    GetMoveNode(allCategories, broCategories.id, moveFuns);

                    //上移
                    if (inputInfo.Flag == 1)
                    {
                        foreach (GoodsCategoriesEntity item in currCat)
                        {
                            item.sort = short.Parse((item.sort - short.Parse(moveFuns.Count.ToString())).ToString());
                            tran.CommandSet<GoodsCategoriesEntity>().Update(item);
                        }

                        foreach (GoodsCategoriesEntity item in moveFuns)
                        {
                            item.sort = short.Parse((item.sort + short.Parse(currCat.Count.ToString())).ToString());
                            tran.CommandSet<GoodsCategoriesEntity>().Update(item);
                        }
                    }
                    else
                    {
                        foreach (GoodsCategoriesEntity item in currCat)
                        {
                            item.sort = short.Parse((item.sort + short.Parse(moveFuns.Count.ToString())).ToString());
                            tran.CommandSet<GoodsCategoriesEntity>().Update(item);
                        }
                        foreach (GoodsCategoriesEntity item in moveFuns)
                        {
                            item.sort = short.Parse((item.sort - short.Parse(currCat.Count.ToString())).ToString());
                            tran.CommandSet<GoodsCategoriesEntity>().Update(item);
                        }
                    }
                });
                result.Code = ActionCodes.Success;
                result.Data = 1;

                AddOperationLog(OperationLogType.ModifyOperation, BusinessTitleType.GoodsCategoriesManage, $"移动顺序操作:{JsonHelper.ToJson(inputInfo)}");
            }
            return result;
        }

        /// <summary>
        /// 上下一定子功能（递归）
        /// </summary>
        /// <param name="allCategories"></param>
        /// <param name="funId"></param>
        /// <param name="move"></param>
        private void GetMoveNode(List<GoodsCategoriesEntity> allCategories, string funId, List<GoodsCategoriesEntity> move)
        {
            List<GoodsCategoriesEntity> borgs = allCategories.FindAll(r => r.parent_id == funId);
            foreach (GoodsCategoriesEntity item in borgs)
            {
                if (item.parent_id == funId)
                {
                    move.Add(item);
                    List<GoodsCategoriesEntity> tempFuns = allCategories.FindAll(r => r.parent_id == item.id);
                    if (tempFuns != null && tempFuns.Count > 0)
                    {
                        GetMoveNode(allCategories, item.id, move);
                    }
                }
            }
        }
        #endregion

        #region 删除信息
        /// <summary>
        /// 删除信息
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public ResultJsonInfo<int> Remove(List<string> ids)
        {
            var resultInfo = new ResultJsonInfo<int>();

            using (var con = DataBase.GetConnection(DatabaseName.Sql_BUS_DB.ToString()))
            {
                var result = 0;
                if (ids.Count >= 0)
                {
                    con.Transaction(tran =>
                    {
                        var listInfo = new List<GoodsCategoriesEntity>();
                        var allInfo = tran.QuerySet<GoodsCategoriesEntity>().ToList();

                        var rootInfo = allInfo.FindAll(p => ids.Contains(p.id));
                        if (rootInfo.Count > 0)
                        {
                            listInfo.AddRange(rootInfo);
                            listInfo.AddRange(allInfo.GetChildList(rootInfo));
                        }
                        var listCode = listInfo.Select(p => p.id).ToList();

                        //判断商品分类下是否有商品
                        int existInfo = tran.QuerySet<GoodsInfoEntity>().Where(p => p.category_id.In(listCode.ToArray())).Count();
                        if (existInfo == 0)
                        {
                            result = tran.CommandSet<GoodsCategoriesEntity>().Where(p => p.id.In(listCode.ToArray())).Delete();
                            if (result > 0)
                            {
                                resultInfo.Code = ActionCodes.Success;
                                resultInfo.Data = result;
                                resultInfo.Msg = "操作成功！";

                                AddOperationLog(OperationLogType.RemoveOperation, BusinessTitleType.GoodsCategoriesManage, $"删除信息:{JsonHelper.ToJson(ids)}");
                            }
                            else
                            {
                                resultInfo.Msg = "操作失败！";
                            }
                        }
                        else
                        {
                            resultInfo.Msg = "选中分类已被已有商品，无法删除！";
                        }
                    });
                }
                else
                {
                    resultInfo.Msg = "id为空，操作失败！";
                }
            }
            return resultInfo;
        }
        #endregion

        #endregion
    }
}
